package com.jin.controller;

import com.jin.pojo.Books;
import com.jin.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    @Qualifier("bookServiceImpl")
    private BookService bookService;

    @RequestMapping("/allBook")
    public String list(Model model){
        List<Books> list = bookService.selectAllBooks();
        model.addAttribute("list",list);
        return "allBook";

    }

    //跳转到增加书籍页面
    @RequestMapping("/toAddBook")
    public String toAddPaper(){
        return "addBook";
    }

    //添加书籍的请求
    @RequestMapping("/addBook")
    public String addBook(Books books){
        System.out.println("addBook="+books);
        bookService.addBooks(books);
        return "redirect:/book/allBook";
    }

    //跳转到修改书籍页面
    @RequestMapping("/toUpdateBook")
    public String  toUpdateBook(int id,Model model){
        Books books = bookService.selectBooksById(id);
        System.out.println("得到的Id为："+id);
        model.addAttribute("book",books);
        return "updateBook";
    }

    //修改书籍
    @RequestMapping("/updateBook")
    public String updateBook(Books books){
        bookService.updateBook(books);
        return "redirect:/book/allBook";
    }

    //删除书籍
    @RequestMapping("/deleteBook/{bookId}")
    public String deleteBook(@PathVariable("bookId") int id){
        bookService.deleteBooksById(id);
        return "redirect:/book/allBook";
    }

    //通过书名查询
    @RequestMapping("/selectBooks")
    //这里的selectBooksByName要和前端的input中的name相同
    public String selectBooksByName(String selectBooksByName,Model model){
        Books books = bookService.selectBooksByName(selectBooksByName);
        System.out.println("查询的书籍为："+books);
        List<Books> list = new ArrayList<>();
        list.add(books);

        if (books == null){
            list = bookService.selectAllBooks();
            model.addAttribute("error","该书籍不存在");
        }

        model.addAttribute("list",list);
        return "allBook";
    }
}
